//
//  LSManyPeopleChatVC.m
//  HappyStore
//
//  Created by 陈锋 on 16/10/8.
//  Copyright © 2016年 LLJ. All rights reserved.
//

#import "LSManyPeopleChatVC.h"
#import "LSTManyPeopleChatCell.h"

@interface LSManyPeopleChatVC ()

@property (nonatomic, strong) NSMutableArray *addressBookArray; // 存放所有的联系人信息
@property(nonatomic,strong)NSMutableArray *indexArray;//索引
@property(nonatomic,strong)NSMutableArray *letterResultArr;//title

@property (strong, nonatomic) NSMutableArray * nameArr;
@property (strong, nonatomic)NSMutableDictionary * modelDict;
@property (strong, nonatomic)NSMutableArray * userListArr;

@property (strong, nonatomic) NSMutableArray * chatArr;
@end

static NSString * searchContactscell = @"LSTManyPeopleChatCell";

@implementation LSManyPeopleChatVC

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"选择好友";
    
    //设置返回按钮
    UIBarButtonItem *leftItem = [UIBarButtonItem itemWithTarget:self action:@selector(leftBarButtonItemClick) image:@"Back" highImage:@"Back"];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    if (self.tlzCYArr) {
        
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
        rightItem.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItem = rightItem;
        
    }else{
    
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"发起" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
        rightItem.tintColor = [UIColor whiteColor];
        self.navigationItem.rightBarButtonItem = rightItem;
    
    }
    
    
    self.tableView.sectionIndexBackgroundColor = [UIColor clearColor];
    self.tableView.sectionIndexTrackingBackgroundColor=[UIColor clearColor];
    
    self.addressBookArray = [[NSMutableArray alloc] init];
    self.nameArr = [[NSMutableArray alloc] init];
    self.indexArray = [[NSMutableArray alloc] init];
    _modelDict = [NSMutableDictionary dictionary];
    
    // 注册
    UINib * nib = [UINib nibWithNibName:@"LSTManyPeopleChatCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:searchContactscell];
    
    self.chatArr = [NSMutableArray array];
    self.userListArr = [NSMutableArray array];
    
    //开启侧滑
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
    [self sendRequest];
}

-(void)rightBarButtonItemClick{
    
    if (self.tlzCYArr) {
        //添加成员
        if (self.chatArr.count >= 1) {
        
            [[RCIMClient sharedRCIMClient] addMemberToDiscussion:self.tlzStr userIdList:self.chatArr success:^(RCDiscussion *discussion) {
                
                dispatch_async(dispatch_get_main_queue(), ^{

                    [self showRoundProgressWithTitle:@"请稍后..."];
                    
                    NSMutableDictionary * dictData = [NSMutableDictionary dictionary];
                    // 添加成员
                    
                    [dictData setValue:allConstMemberToken forKey:@"token"];
                    [dictData setValue:self.userListArr forKey:@"joinUserIds"];
                    [dictData setValue:self.tlzStr forKey:@"groupId"];
  
                    NSString *jsonStr = nil;
                    jsonStr = [LSHttpTool DataTOjsonString:self.userListArr];
                    [dictData setValue:jsonStr forKey:@"joinUserIds"];
                    
                    NSString *str = @"addCircleMember_app_social.im.lensum?";
                    
                    [LSHttpTool sendHttpData:str params:dictData success:^(id responseObject) {
                        
                        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
                        
                        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {

                            [self hideBubble];
                            
                            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"成功添加成员!" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil];
                            [alert show];
                            
                            [self.navigationController popViewControllerAnimated:YES];
                            
                        }
                        
                        
                    } failure:^(NSError *error) {

                        [self showSingleIconBubble:@"网络连接错误"];
                        
                    }];

                
                });
                
            } error:^(RCErrorCode status) {
                NSLog(@"create discussion Failed &gt; %ld!", (long)status);
            }];
        
        }else{
        
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"人数不得少于1人!" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil];
            [alert show];
        
        }
        
    }else{
    
        //发起讨论组
    
    [self.chatArr addObject:[USER_DEFAULTS objectForKey:@"account"]];
//    [self.userListArr addObject:[USER_DEFAULTS objectForKey:@"userid"]];
    NSLog(@"%@",self.chatArr);
    
    if (self.chatArr.count > 1) {
        
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请输入群组名称" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"发起",nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *nameField = [alert textFieldAtIndex:0];
    nameField.placeholder = @"请输入群组名称";
    nameField.keyboardType = UIKeyboardTypeDefault;
    
    [alert showAlertWithCompletionHandler:^(NSInteger buttonIndex) {
        if(buttonIndex == 1){
            UITextField *tf=[alert textFieldAtIndex:0];
            if (tf.text.length > 0) {
                
                [[RCIMClient sharedRCIMClient] createDiscussion:tf.text userIdList:self.chatArr success:^(RCDiscussion *discussion) {

                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        NSLog(@"讨论组回调:讨论组ID:%@,讨论组名称:%@,讨论组创建者ID:%@",discussion.discussionId,discussion.discussionName,discussion.creatorId);

                        [self showRoundProgressWithTitle:@"请稍后..."];
                        
                        sessionVC *chat =[[sessionVC alloc]init];
                        chat.targetId = discussion.discussionId;
                        chat.conversationType = ConversationType_DISCUSSION;
                        chat.title = tf.text;
                        
                        NSMutableDictionary * dict = [NSMutableDictionary dictionary];
                        dict[@"discussionId"] = discussion.discussionId;
                        dict[@"creatorId"] = discussion.creatorId;
                        dict[@"discussionName"] = tf.text;
                        
                        NSMutableArray * mtArr = [NSMutableArray array];
                        [mtArr addObject:dict];
                        
                        [USER_DEFAULTS setObject:mtArr forKey:@"TaoLunZu"];
                        
                        chat.tlzDict = dict;
                        chat.style = @"讨论组";
                        
                        NSMutableDictionary * dictData = [NSMutableDictionary dictionary];
                        
                        // 服务器备份
                        
                        [dictData setValue:allConstMemberToken forKey:@"token"];
                        [dictData setValue:allConstMemberid forKey:@"userId"];
                        [dictData setValue:discussion.discussionId forKey:@"groupId"];
                        [dictData setValue:tf.text forKey:@"groupName"];
                        NSString *jsonStr = nil;
                        jsonStr = [LSHttpTool DataTOjsonString:self.userListArr];
                        [dictData setValue:jsonStr forKey:@"joinUserIds"];
                        
                        NSString *str = @"addCircle_app_social.im.lensum?";
                        
                        [LSHttpTool sendHttpData:str params:dictData success:^(id responseObject) {
                            
                            NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
                            
                            if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
                                
                                IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
                                manager.enable = NO;
                                manager.shouldResignOnTouchOutside = NO;
                                manager.shouldToolbarUsesTextFieldTintColor = NO;
                                manager.enableAutoToolbar = NO;

                                [self hideBubble];
                                [self.navigationController pushViewController:chat animated:YES];
                                
                            }
 
                            
                        } failure:^(NSError *error) {

                            [self showSingleIconBubble:@"网络连接错误"];
                            
                        }];
                        
                    });
                } error:^(RCErrorCode status) {
                    NSLog(@"create discussion Failed &gt; %ld!", (long)status);
                }];
            }
        }
    }];
        
    }else{
    
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"人数不得少于2人!" delegate:self cancelButtonTitle:@"知道了" otherButtonTitles: nil];
        [alert show];
    
    }
        
    }
}



-(void)leftBarButtonItemClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source

-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    
    return self.indexArray;
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    [tableView tableViewDisplayWitMsg:@"没有查询到相对应的数据" ifNecessaryForRowCount:self.indexArray.count];
    
    return self.indexArray.count;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return [[self.letterResultArr objectAtIndex:section] count];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    
    return index;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75.0;
}

//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
//
//        NSString *key = [self.indexArray objectAtIndex:section];
//        return key;
//}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0;
    
}

//-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//
//    return 20;
//
//}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    view.backgroundColor = RGB(247, 247, 247);
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(14, 2, screenW, 21)];
    
    titleLabel.textColor = RGB(117, 117, 117);
    titleLabel.font = [UIFont systemFontOfSize:14];
    NSString *key = [self.indexArray objectAtIndex:section];
    titleLabel.text = key;
    
    [view addSubview:titleLabel];
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSTManyPeopleChatCell *cell = [tableView dequeueReusableCellWithIdentifier:searchContactscell forIndexPath:indexPath];
    
    NSString * name = [[self.letterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row];
    
    NSDictionary * dict = [_modelDict valueForKey:name];
    
    cell.lineView.hidden = YES;
    
    [cell.headImg sd_setImageWithURL:[NSURL URLWithString:dict[@"headPhoto"]]];
    cell.headImg.layer.masksToBounds = YES;
    cell.headImg.layer.cornerRadius = 5.0f;
    
    if ([dict[@"userName"] isEqualToString:@""] || [dict[@"userName"] isEqualToString:@"null"]) {
        cell.nameLabel.text = dict[@"account"];
    }else{
        cell.nameLabel.text = dict[@"userName"];
    }
    
    CGSize size = [cell.nameLabel sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    if (size.width<190) {
        [cell.nameLabel setFrame:CGRectMake(cell.nameLabel.x, cell.nameLabel.y, size.width, cell.nameLabel.height)];
    }else{
        [cell.nameLabel setFrame:CGRectMake(cell.nameLabel.x, cell.nameLabel.y, 168, cell.nameLabel.height)];
    }
    
    cell.lineView.x = cell.nameLabel.x + cell.nameLabel.width + 2;
    
    
    
    if ([dict[@"positionName"] isEqualToString:@""] || [dict[@"positionName"] isEqualToString:@"null"]) {
        cell.posName.text = @"";
    }else{
        cell.posName.text = dict[@"positionName"];
    }
    
    CGSize posSize = [cell.posName sizeThatFits:CGSizeMake(MAXFLOAT, 21)];
    
    if (posSize.width <= 60) {
        cell.posName.width = posSize.width;
    }else{
        cell.posName.width = 60;
    }
    
    
    cell.posName.x = cell.lineView.x;
    cell.vImg.x = cell.posName.x + cell.posName.width + 2;
    if (cell.vImg.x > 185) {
        cell.vImg.x = 184;
    }
    
    
    cell.lineView.hidden = YES;
    //上级
    cell.detailLabel.text = [UsedTool userType:dict[@"userType"] companyName:dict[@"companyName"] userAddress:dict[@"userAddress"]];
    
    //    if ([dict[@"authState"]integerValue] == 2) {
    //        cell.vImg.image = [UIImage imageNamed:@"yirenzheng"];
    //    }else{
    //        cell.vImg.image = [UIImage imageNamed:@"weirenzheng"];
    //    }
    //认证
    cell.isAuthState.hidden = [UsedTool authStateImageViewHidden:dict[@"authState"]];
    //会员图标
    cell.vImg.image = [UsedTool setVipimage:dict[@"vipLevel"]];
    
    [cell.changeBtn addTarget:self action:@selector(changeBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.changeBtn.titleLabel.text = name;
    
    if (self.tlzCYArr) {
        
        for (NSDictionary * dic in self.tlzCYArr) {
            
            if ([dic[@"account"] isEqualToString:dict[@"account"]]) {
                cell.changeBtn.selected = YES;
                cell.changeBtn.userInteractionEnabled = NO;
            }
            
        }
    }//添加成员
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中状态
    
    
}

#pragma mark - 选择按钮
-(void)changeBtn:(UIButton *)sender{

//    NSLog(@"%@",sender.titleLabel.text);
    sender.selected = !sender.selected;
    NSLog(@"%@",sender.selected?@"YES":@"NO");
    
    NSDictionary * dict = [_modelDict valueForKey:sender.titleLabel.text];
//    NSLog(@"%@",dict);
    
    if (sender.selected == YES) {
        
        if (![self.chatArr containsObject:dict[@"account"]] && ![self.userListArr containsObject:dict[@"userId"]]) {
            [self.chatArr addObject:dict[@"account"]];
            [self.userListArr addObject:dict[@"userId"]];
        }
        
    }else if(sender.selected == NO){
    
        [self.chatArr removeObject:dict[@"account"]];
        [self.userListArr removeObject:dict[@"userId"]];
    
    }
}

#pragma mark - 请求数据

-(void)sendRequest{

    [self showRoundProgressWithTitle:@"请稍后..."];
    NSMutableDictionary *muDicParameters = [NSMutableDictionary dictionary];
    
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"userid"] forKey:@"userId"];
    [muDicParameters setObject:[USER_DEFAULTS objectForKey:@"token"] forKey:@"token"];//验证用户
    
    NSString *strURl = [NSString stringWithFormat:@"%@%@",URL_DEFINE,@"getMyFriend_app_social.im.lensum"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager POST:strURl parameters:muDicParameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dicInfo = [NSDictionary dictionaryWithDictionary:responseObject];
        
        if ([[dicInfo objectForKey:@"result"] integerValue] == 1) {
            
            self.addressBookArray = dicInfo[@"data"][@"record"];
            
            //解析数据
            for (NSDictionary * dict in self.addressBookArray) {
                
                [self.nameArr addObject:dict[@"userName"]];
                [_modelDict setValue:dict forKey:dict[@"userName"]];
                
            }
            
            self.indexArray = [ChineseString IndexArray:_nameArr];
            self.letterResultArr = [ChineseString LetterSortArray:_nameArr];

            [self hideBubble];
            
        }else {
            
            [self showSingleIconBubble:[dicInfo objectForKey:@"msg"]];
        }
        
        [self.tableView reloadData];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

       [self showSingleIconBubble:error.localizedDescription];
    }];
    
    
}

@end
